package com.zhao.fishingguideserver.mapper;

import com.zhao.fishingguideserver.POJO.AdminUser;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 管理员数据访问接口
 */
@Mapper
public interface AdminUserMapper {
    
    /**
     * 根据用户名查询管理员
     */
    @Select("SELECT admin_id as adminId, username, password, nick_name as nickName, role, status, " +
            "created_at as createdAt, updated_at as updatedAt " +
            "FROM admin_user WHERE username = #{username}")
    AdminUser selectByUsername(String username);
    
    /**
     * 根据ID查询管理员
     */
    @Select("SELECT admin_id as adminId, username, password, nick_name as nickName, role, status, " +
            "created_at as createdAt, updated_at as updatedAt " +
            "FROM admin_user WHERE admin_id = #{adminId}")
    AdminUser selectById(Long adminId);
    
    /**
     * 查询所有管理员（分页）
     */
    @Select("<script>" +
            "SELECT admin_id as adminId, username, nick_name as nickName, role, status, " +
            "created_at as createdAt, updated_at as updatedAt " +
            "FROM admin_user " +
            "<where>" +
            "<if test='username != null and username != \"\"'>" +
            "AND username LIKE CONCAT('%', #{username}, '%')" +
            "</if>" +
            "<if test='role != null and role != \"\"'>" +
            "AND role = #{role}" +
            "</if>" +
            "<if test='status != null'>" +
            "AND status = #{status}" +
            "</if>" +
            "</where>" +
            "ORDER BY created_at DESC " +
            "</script>")
    List<AdminUser> selectAll(@Param("username") String username, 
                              @Param("role") String role, 
                              @Param("status") Integer status);
    
    /**
     * 插入管理员
     */
    @Insert("INSERT INTO admin_user(username, password, nick_name, role, status, created_at) " +
            "VALUES(#{username}, #{password}, #{nickName}, #{role}, #{status}, now())")
    @Options(useGeneratedKeys = true, keyProperty = "adminId")
    int insert(AdminUser adminUser);
    
    /**
     * 更新管理员信息
     */
    @Update("<script>" +
            "UPDATE admin_user " +
            "<set>" +
            "<if test='nickName != null'>nick_name = #{nickName},</if>" +
            "<if test='password != null'>password = #{password},</if>" +
            "<if test='role != null'>role = #{role},</if>" +
            "<if test='status != null'>status = #{status},</if>" +
            "updated_at = now()" +
            "</set>" +
            "WHERE admin_id = #{adminId}" +
            "</script>")
    int update(AdminUser adminUser);
    
    /**
     * 删除管理员
     */
    @Delete("DELETE FROM admin_user WHERE admin_id = #{adminId}")
    int deleteById(Long adminId);
    
    /**
     * 统计管理员数量
     */
    @Select("SELECT COUNT(*) FROM admin_user WHERE status = 1")
    int countTotal();
}

